<template>
  <div style="background-color: #fff; padding-top: 8px">
    <el-form :model="form" ref="form" label-width="100px">
      <el-form-item label="系统名称:">
        <el-tag type="success" size="medium">{{ SystemName }}</el-tag>
      </el-form-item>
      <el-form-item label="角色名称:">
        <span>{{ RoleName }}</span></el-form-item
      >
    </el-form>
    <div style="padding: 0 18px 18px 18px">
      <el-table
        :data="tableData"
        style="width: 100%"
        border
        :header-cell-style="{
          background: '#F5F7FA',
          color: '#303133',
          'text-align': 'center',
        }"
        :default-expand-all="true"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="type" label="功能模块" width="300px">
          <template slot-scope="scope">
            {{ scope.row.type }}
          </template>
        </el-table-column>
        <el-table-column prop="date" label="操作权限" width="auto">
          <template slot-scope="scope">
            <el-checkbox
              :indeterminate="scope.row.isIndeterminate"
              v-model="scope.row.checkAll"
              @change="handleCheckAllChange($event, scope.row.id)"
              v-if="scope.row.options.length != 0"
              >全选</el-checkbox
            >
            <el-checkbox-group
              v-model="scope.row.value"
              @change="handleCheckedCitiesChange($event, scope.row.id)"
            >
              <el-checkbox
                :label="item.value"
                v-for="(item, index) in scope.row.options"
                :key="index"
                >{{ item.label }}</el-checkbox
              >
            </el-checkbox-group>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="height: 56px">
      <div style="margin: 0 18px 18px 0; float: right">
        <el-button plain>返 回</el-button>

        <el-button type="primary" @click="submit" :loading="loading"
          >确 定</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import {
  AccessRole_GetPermissionsSetTree,
  AccessRole_PermissionsSetPost,
} from "@/api/business";
export default {
  name: "VueXuAdminOperate",

  data() {
    return {
      SystemName: JSON.parse(localStorage.getItem("xmGlDetails")).SystemName,
      RoleName: JSON.parse(localStorage.getItem("xmGlSzQx")).RoleName,
      tableData: [
       
      ],
      form: {
        name: "",
        status: "",
      },
      value: "",
      ids: [],
      loading: false,
    };
  },

  mounted() {
    this.getData();
  },

  methods: {
    async getData() {
      let data = {
        managementId: JSON.parse(localStorage.getItem("xmGlSzQx")).ManagementId,
        roleId: JSON.parse(localStorage.getItem("xmGlSzQx")).Id,
      };
      let res = await AccessRole_GetPermissionsSetTree(data);
     

      this.tableData = res.data.response;

      const recursiveFind = (items) => {
        for (let i = 0; i < items.length; i++) {
          const item = items[i];

         if(item.ids&&item.ids.length!=0){
          item.value=item.ids
         }
       
          if (item.children && item.children.length > 0) {
            recursiveFind(item.children);
          }
        }
      };

      recursiveFind(this.tableData);
    },
    handleCheckAllChange(val, id) {
      console.log(val, id);
      this.findById(val, id);
    },
    handleCheckedCitiesChange(len, id) {
      console.log(len, id);
      this.findByLength(len, id);
    },
    findByLength(len, id) {
      console.log(len,"len234")
      if (this.tableData) {
        const recursiveFind = (items) => {
          for (let i = 0; i < items.length; i++) {
            const item = items[i];
            if (item.id === id) {
              const length = len.length;
              item.checkAll = length === item.options.length;
              item.isIndeterminate = length > 0 && length < item.options.length;
              item.ids = len;
              // if (item.ids) {
              //   item.ids.splice(id, 1);
              // } else {
              //   item.ids.push(id);
              // }
            } else if (item.children && item.children.length > 0) {
              recursiveFind(item.children);
            }
          }
        };
        recursiveFind(this.tableData);
      }
    },
    findById(val, id) {
      if (this.tableData) {
        const recursiveFind = (items) => {
          for (let i = 0; i < items.length; i++) {
            const item = items[i];
            if (item.id === id) {
              const values = [];
              const ids = [];
              item.options.forEach((element) => {
                values.push(element.value);
                ids.push(element.value);
              });
              item.value = val ? values : [];
              item.isIndeterminate = false;
              item.ids = ids;
            } else if (item.children && item.children.length > 0) {
              recursiveFind(item.children);
            }
          }
        };

        recursiveFind(this.tableData);
      }
    },
    async submit() {
      console.log(this.tableData);
      this.loading = true;
      const recursiveFind = (items) => {
        const ids = []; // 保存ID的数组

        if (Array.isArray(items)) {
          items.forEach((item) => {
            ids.push(...recursiveFind(item)); // 调用递归函数处理子节点
          });
        } else {
          // ids.push(items.id); // 添加当前节点的ID到数组中
          // if (items.value) {
          //   ids.push(...items.value);
          // }
          ids.push(...items.value);

          if (items.children && Array.isArray(items.children)) {
            ids.push(...recursiveFind(items.children)); // 调用递归函数处理子节点
          }
        }

        return ids;
      };

      const idsArr = recursiveFind(this.tableData);
      console.log(idsArr, "idsArr");
      const data = {
        RoleId: JSON.parse(localStorage.getItem("xmGlSzQx")).Id,
        ModulesIds: idsArr,
      };
    
      const res = await AccessRole_PermissionsSetPost(data);
      console.log(res);
      if (res.data.success) {
        this.loading = false;
        this.dialog = false;
        this.$message({
          type: "success",
          message: res.data.msg,
        });
      } else {
        this.loading = false;
        this.$message({
          type: "error",
          message: res.data.msg,
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped></style>
